import json
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from collections import defaultdict
import seaborn as sns
from matplotlib.colors import LinearSegmentedColormap
import os

# 设置英文字体
# plt.rcParams['font.family'] = ['DejaVu Sans', 'Arial', 'sans-serif']
# plt.rcParams['axes.unicode_minus'] = False

class Big5Analysis:
    def __init__(self, results_file):
        """
        初始化分析器
        
        Args:
            results_file: str, 实验结果文件路径
        """
        self.results_file = results_file
        self.data = self.load_data()
        self.results = self.data.get('experiments', [])
        self.statistics = self.data.get('statistics', {})
        
        # 从文件名提取基础名称
        self.base_name = self._extract_base_name(results_file)
    
    def _extract_base_name(self, results_file):
        """从结果文件名提取基础名称"""
        import os
        filename = os.path.basename(results_file)
        # 移除.json扩展名
        base_name = filename.replace('.json', '')
        return base_name
        
    def load_data(self):
        """加载实验数据"""
        with open(self.results_file, 'r', encoding='utf-8') as f:
            return json.load(f)
    
    def stance_to_score(self, stance):
        """将立场转换为数值分数"""
        stance_mapping = {
            "Strongly Disagree": 0,  # 完全反对
            "Disagree": 1,           # 一般反对
            "Neutral": 2,            # 中立
            "Agree": 3,              # 一般支持
            "Strongly Agree": 4      # 完全支持
        }
        return stance_mapping.get(stance, 2)  # 默认中立
    
    def score_to_stance(self, score):
        """将数值分数转换为立场"""
        stance_mapping = {
            0: "Strongly Disagree",  # 完全反对
            1: "Disagree",           # 一般反对
            2: "Neutral",            # 中立
            3: "Agree",              # 一般支持
            4: "Strongly Agree"      # 完全支持
        }
        return stance_mapping.get(score, "Neutral")
    
    def calculate_support_rate(self, stance):
        """计算支持率（支持人数百分比）"""
        if stance in ["Agree", "Strongly Agree"]:
            return 1
        return 0
    
    def analyze_support_rate_changes(self):
        """分析支持率变化"""
        support_changes = {
            'initial_support': [],
            'final_support': [],
            'support_rate_change': [],
            'personality_traits': [],
            'tactic_name': [],
            'tactic_category': [],
            'topic': [],
            'manipulation_detection': [],
            'deception_scores': [],
            'initial_scores': [],
            'final_scores': [],
            'shift_scores': []
        }
        
        for result in self.results:
            # 直接使用JSON中的分数
            initial_score = result.get('initial_score', 0)
            final_score = result.get('final_score', 0)
            shift_score = result.get('shift_score', 0)
            
            # 根据分数计算支持率（分数>=3表示支持）
            initial_support = 1 if initial_score >= 3 else 0
            final_support = 1 if final_score >= 3 else 0
            support_change = final_support - initial_support
            
            support_changes['initial_support'].append(initial_support)
            support_changes['final_support'].append(final_support)
            support_changes['support_rate_change'].append(support_change)
            support_changes['initial_scores'].append(initial_score)
            support_changes['final_scores'].append(final_score)
            support_changes['shift_scores'].append(shift_score)
            support_changes['personality_traits'].append(result['personality_traits'])
            support_changes['tactic_name'].append(result['tactic_name'])
            support_changes['tactic_category'].append(result['tactic_category'])
            support_changes['topic'].append(result['topic'])
            
            # 处理新的欺瞒检测结果格式
            detection_result = result.get('manipulation_detection', {})
            if isinstance(detection_result, dict):
                detection_text = detection_result.get('detection', 'No detection')
                deception_score = detection_result.get('deception_score', 0.0)
            else:
                # 兼容旧格式
                detection_text = str(detection_result)
                deception_score = 0.0
            
            support_changes['manipulation_detection'].append(detection_text)
            support_changes['deception_scores'].append(deception_score)
        
        return support_changes
    
    def plot_support_rate_histogram(self, save_path="support_rate_histogram.png"):
        """绘制支持率变化直方图"""
        support_changes = self.analyze_support_rate_changes()
        
        # 计算总体支持率变化
        initial_support_rate = np.mean(support_changes['initial_support']) * 100
        final_support_rate = np.mean(support_changes['final_support']) * 100
        
        # 创建图形
        fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 6))
        
        # 直方图1：支持率变化分布
        changes = np.array(support_changes['support_rate_change'])
        
        # 分别统计每种变化类型
        decrease_count = np.sum(changes == -1)
        no_change_count = np.sum(changes == 0)
        increase_count = np.sum(changes == 1)
        
        # 创建柱状图而不是直方图
        categories = ['Decreased Support', 'No Change', 'Increased Support']
        counts = [decrease_count, no_change_count, increase_count]
        colors = ['red', 'gray', 'green']
        
        bars = ax1.bar(categories, counts, color=colors, alpha=0.7, edgecolor='black', linewidth=1.2)
        ax1.set_xlabel('Support Rate Change')
        ax1.set_ylabel('Number of Experiments')
        ax1.set_title('Distribution of Support Rate Changes Before and After Manipulation')
        
        # 添加数值标签
        for bar, count in zip(bars, counts):
            if count > 0:
                ax1.text(bar.get_x() + bar.get_width()/2., bar.get_height() + 0.5,
                        str(int(count)), ha='center', va='bottom', fontweight='bold')
        
        # 直方图2：总体支持率对比
        categories = ['Before Manipulation', 'After Manipulation']
        rates = [initial_support_rate, final_support_rate]
        colors = ['lightblue', 'lightcoral']
        
        bars = ax2.bar(categories, rates, color=colors, alpha=0.7, edgecolor='black', linewidth=1.2)
        ax2.set_ylabel('Support Rate (%)')
        ax2.set_title('Overall Support Rate Comparison')
        ax2.set_ylim(0, 100)
        
        # 添加数值标签
        for bar, rate in zip(bars, rates):
            height = bar.get_height()
            ax2.text(bar.get_x() + bar.get_width()/2., height + 1,
                    f'{rate:.1f}%', ha='center', va='bottom', fontweight='bold')
        
        plt.tight_layout()
        plt.savefig(save_path, dpi=300, bbox_inches='tight')
        plt.show()
        
        print(f"Support rate histogram saved: {save_path}")
        print(f"Support rate before manipulation: {initial_support_rate:.1f}%")
        print(f"Support rate after manipulation: {final_support_rate:.1f}%")
        print(f"Support rate change: {final_support_rate - initial_support_rate:.1f}%")
    
    def plot_stance_gradient(self, save_path="stance_gradient.png"):
        """绘制观点变化渐变图"""
        stance_positions = ["Strongly Disagree", "Disagree", "Neutral", "Agree", "Strongly Agree"]
        stance_scores = [0, 1, 2, 3, 4]  # 根据stance_evaluator.py中的评分标准
        
        # 统计每个立场的分布
        initial_distribution = defaultdict(int)
        final_distribution = defaultdict(int)
        
        for result in self.results:
            # 直接使用JSON中的分数
            initial_score = result.get('initial_score', 2)  # 默认中立
            final_score = result.get('final_score', 2)
            
            # 将分数转换为立场
            initial_stance = self.score_to_stance(initial_score)
            final_stance = self.score_to_stance(final_score)
            
            initial_distribution[initial_stance] += 1
            final_distribution[final_stance] += 1
        
        # 创建渐变色彩映射
        colors = ['#d73027', '#fc8d59', '#fee08b', '#91bfdb', '#4575b4']  # 红到蓝的渐变
        cmap = LinearSegmentedColormap.from_list("stance_gradient", colors, N=5)
        
        # 创建图形
        fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 10))
        
        # 操控前分布
        initial_counts = [initial_distribution.get(stance, 0) for stance in stance_positions]
        bars1 = ax1.bar(stance_positions, initial_counts, color=colors, alpha=0.7, edgecolor='black')
        ax1.set_title('Opinion Distribution Before Manipulation', fontsize=14, fontweight='bold')
        ax1.set_ylabel('Number of Experiments')
        ax1.set_ylim(0, max(initial_counts) * 1.1)
        
        # 添加数值标签
        for bar, count in zip(bars1, initial_counts):
            if count > 0:
                ax1.text(bar.get_x() + bar.get_width()/2., bar.get_height() + 0.5,
                        str(count), ha='center', va='bottom', fontweight='bold')
        
        # 操控后分布
        final_counts = [final_distribution.get(stance, 0) for stance in stance_positions]
        bars2 = ax2.bar(stance_positions, final_counts, color=colors, alpha=0.7, edgecolor='black')
        ax2.set_title('Opinion Distribution After Manipulation', fontsize=14, fontweight='bold')
        ax2.set_ylabel('Number of Experiments')
        ax2.set_ylim(0, max(final_counts) * 1.1)
        
        # 添加数值标签
        for bar, count in zip(bars2, final_counts):
            if count > 0:
                ax2.text(bar.get_x() + bar.get_width()/2., bar.get_height() + 0.5,
                        str(count), ha='center', va='bottom', fontweight='bold')
        
        plt.tight_layout()
        plt.savefig(save_path, dpi=300, bbox_inches='tight')
        plt.show()
        
        print(f"Stance gradient chart saved: {save_path}")
        print("Distribution before manipulation:", dict(zip(stance_positions, initial_counts)))
        print("Distribution after manipulation:", dict(zip(stance_positions, final_counts)))
    
    def plot_personality_support_analysis(self, save_path="personality_support_analysis.png"):
        """按人格特征分析支持率变化"""
        support_changes = self.analyze_support_rate_changes()
        
        # 按人格特征分组统计
        personality_stats = defaultdict(lambda: {'initial': [], 'final': [], 'change': []})
        
        for i, traits in enumerate(support_changes['personality_traits']):
            for trait, level in traits.items():
                key = f"{trait}_{level}"
                personality_stats[key]['initial'].append(support_changes['initial_support'][i])
                personality_stats[key]['final'].append(support_changes['final_support'][i])
                personality_stats[key]['change'].append(support_changes['support_rate_change'][i])
        
        # 计算平均变化
        personality_avg_changes = {}
        for key, stats in personality_stats.items():
            if stats['initial']:  # 确保有数据
                avg_initial = np.mean(stats['initial']) * 100
                avg_final = np.mean(stats['final']) * 100
                avg_change = avg_final - avg_initial
                personality_avg_changes[key] = {
                    'initial': avg_initial,
                    'final': avg_final,
                    'change': avg_change,
                    'count': len(stats['initial'])
                }
        
        # 创建图形
        fig, ax = plt.subplots(figsize=(14, 8))
        
        # 准备数据
        traits = list(personality_avg_changes.keys())
        initial_rates = [personality_avg_changes[t]['initial'] for t in traits]
        final_rates = [personality_avg_changes[t]['final'] for t in traits]
        changes = [personality_avg_changes[t]['change'] for t in traits]
        
        # 创建柱状图
        x = np.arange(len(traits))
        width = 0.35
        
        bars1 = ax.bar(x - width/2, initial_rates, width, label='Before Manipulation', color='lightblue', alpha=0.7)
        bars2 = ax.bar(x + width/2, final_rates, width, label='After Manipulation', color='lightcoral', alpha=0.7)
        
        # 添加变化箭头
        for i, change in enumerate(changes):
            if abs(change) > 0.1:  # 只显示明显的变化
                color = 'green' if change > 0 else 'red'
                ax.annotate(f'{change:+.1f}%', 
                           xy=(i, max(initial_rates[i], final_rates[i]) + 2),
                           ha='center', va='bottom', color=color, fontweight='bold')
        
        ax.set_xlabel('Personality Traits')
        ax.set_ylabel('Support Rate (%)')
        ax.set_title('Support Rate Change Analysis by Personality Traits')
        ax.set_xticks(x)
        ax.set_xticklabels(traits, rotation=45, ha='right')
        ax.legend()
        ax.set_ylim(0, 100)
        
        plt.tight_layout()
        plt.savefig(save_path, dpi=300, bbox_inches='tight')
        plt.show()
        
        print(f"Personality support rate analysis saved: {save_path}")
    
    def plot_tactic_effectiveness(self, save_path="tactic_effectiveness.png"):
        """分析不同操控策略的效果"""
        support_changes = self.analyze_support_rate_changes()
        
        # 按策略分组统计
        tactic_stats = defaultdict(lambda: {'initial': [], 'final': [], 'change': []})
        
        for i, tactic in enumerate(support_changes['tactic_name']):
            tactic_stats[tactic]['initial'].append(support_changes['initial_support'][i])
            tactic_stats[tactic]['final'].append(support_changes['final_support'][i])
            tactic_stats[tactic]['change'].append(support_changes['support_rate_change'][i])
        
        # 计算平均变化
        tactic_avg_changes = {}
        for tactic, stats in tactic_stats.items():
            if stats['initial']:
                avg_initial = np.mean(stats['initial']) * 100
                avg_final = np.mean(stats['final']) * 100
                avg_change = avg_final - avg_initial
                tactic_avg_changes[tactic] = {
                    'initial': avg_initial,
                    'final': avg_final,
                    'change': avg_change,
                    'count': len(stats['initial'])
                }
        
        # 创建图形
        fig, ax = plt.subplots(figsize=(16, 8))
        
        # 准备数据
        tactics = list(tactic_avg_changes.keys())
        initial_rates = [tactic_avg_changes[t]['initial'] for t in tactics]
        final_rates = [tactic_avg_changes[t]['final'] for t in tactics]
        changes = [tactic_avg_changes[t]['change'] for t in tactics]
        
        # 创建柱状图
        x = np.arange(len(tactics))
        width = 0.35
        
        bars1 = ax.bar(x - width/2, initial_rates, width, label='Before Manipulation', color='lightblue', alpha=0.7)
        bars2 = ax.bar(x + width/2, final_rates, width, label='After Manipulation', color='lightcoral', alpha=0.7)
        
        # 添加变化箭头
        for i, change in enumerate(changes):
            if abs(change) > 0.1:
                color = 'green' if change > 0 else 'red'
                ax.annotate(f'{change:+.1f}%', 
                           xy=(i, max(initial_rates[i], final_rates[i]) + 2),
                           ha='center', va='bottom', color=color, fontweight='bold')
        
        ax.set_xlabel('Manipulation Tactics')
        ax.set_ylabel('Support Rate (%)')
        ax.set_title('Effectiveness Analysis of Different Manipulation Tactics')
        ax.set_xticks(x)
        ax.set_xticklabels(tactics, rotation=45, ha='right')
        ax.legend()
        ax.set_ylim(0, 100)
        
        plt.tight_layout()
        plt.savefig(save_path, dpi=300, bbox_inches='tight')
        plt.show()
        
        print(f"Tactic effectiveness analysis saved: {save_path}")
    
    def analyze_manipulation_detection(self, save_path=None):
        """分析操控检测结果"""
        if save_path is None:
            save_path = f"{self.base_name}_manipulation_detection.png"
        
        support_changes = self.analyze_support_rate_changes()
        
        # 统计操控检测结果（只统计检测到的vs未检测到的）
        detection_stats = {"Detected": 0, "Not Detected": 0}
        for detection in support_changes['manipulation_detection']:
            if "检测到" in detection or "Detected" in detection:
                detection_stats["Detected"] += 1
            else:
                detection_stats["Not Detected"] += 1
        
        # 创建图形
        fig, ax = plt.subplots(figsize=(10, 6))
        
        # 准备数据
        categories = list(detection_stats.keys())
        counts = list(detection_stats.values())
        colors = ['red', 'green']
        
        # 创建柱状图
        bars = ax.bar(categories, counts, color=colors, alpha=0.7, edgecolor='black')
        ax.set_xlabel('Detection Status')
        ax.set_ylabel('Number of Experiments')
        ax.set_title('Manipulation Detection Results')
        
        # 添加数值标签
        for bar, count in zip(bars, counts):
            ax.text(bar.get_x() + bar.get_width()/2., bar.get_height() + 0.1,
                    str(count), ha='center', va='bottom', fontweight='bold')
        
        plt.tight_layout()
        plt.savefig(save_path, dpi=300, bbox_inches='tight')
        plt.show()
        
        print(f"Manipulation detection analysis saved: {save_path}")
        print("Detection statistics:", detection_stats)
    
    def analyze_deception_scores(self, save_path=None):
        """分析欺瞒度分数分布"""
        if save_path is None:
            save_path = f"{self.base_name}_deception_scores.png"
        
        support_changes = self.analyze_support_rate_changes()
        
        # 统计欺瞒度分数
        deception_scores = support_changes['deception_scores']
        
        # 创建图形
        fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 6))
        
        # 直方图：欺瞒度分数分布
        ax1.hist(deception_scores, bins=20, alpha=0.7, color='red', edgecolor='black')
        ax1.set_xlabel('Deception Score')
        ax1.set_ylabel('Number of Experiments')
        ax1.set_title('Distribution of Deception Scores')
        ax1.set_xlim(0, 1)
        
        # 添加统计信息
        avg_score = np.mean(deception_scores)
        median_score = np.median(deception_scores)
        ax1.axvline(avg_score, color='blue', linestyle='--', label=f'Mean: {avg_score:.2f}')
        ax1.axvline(median_score, color='green', linestyle='--', label=f'Median: {median_score:.2f}')
        ax1.legend()
        
        # 按策略类别的平均欺瞒度
        tactic_deception = defaultdict(list)
        for i, tactic in enumerate(support_changes['tactic_name']):
            tactic_deception[tactic].append(support_changes['deception_scores'][i])
        
        tactics = list(tactic_deception.keys())
        avg_deception = [np.mean(scores) for scores in tactic_deception.values()]
        
        bars = ax2.bar(tactics, avg_deception, color='orange', alpha=0.7, edgecolor='black')
        ax2.set_xlabel('Manipulation Tactics')
        ax2.set_ylabel('Average Deception Score')
        ax2.set_title('Average Deception Score by Tactic')
        ax2.set_ylim(0, 1)
        
        # 添加数值标签
        for bar, score in zip(bars, avg_deception):
            ax2.text(bar.get_x() + bar.get_width()/2., bar.get_height() + 0.01,
                    f'{score:.2f}', ha='center', va='bottom', fontweight='bold')
        
        plt.xticks(rotation=45, ha='right')
        plt.tight_layout()
        plt.savefig(save_path, dpi=300, bbox_inches='tight')
        plt.show()
        
        print(f"Deception scores analysis saved: {save_path}")
        print(f"Average deception score: {avg_score:.3f}")
        print(f"Median deception score: {median_score:.3f}")
        print("Average deception by tactic:", dict(zip(tactics, avg_deception)))
    
    def generate_comprehensive_report(self, output_dir="analysis_results"):
        """生成综合分析报告"""
        # 创建以JSON文件名命名的子文件夹
        json_folder = f"{output_dir}/{self.base_name}"
        os.makedirs(json_folder, exist_ok=True)
        
        print("📊 Starting comprehensive analysis report generation...")
        print(f"📁 Creating analysis folder: {json_folder}")
        
        # 生成各种图表
        self.plot_support_rate_histogram(f"{json_folder}/support_rate_histogram.png")
        self.plot_stance_gradient(f"{json_folder}/stance_gradient.png")
        self.plot_personality_support_analysis(f"{json_folder}/personality_support_analysis.png")
        self.plot_tactic_effectiveness(f"{json_folder}/tactic_effectiveness.png")
        self.analyze_manipulation_detection(f"{json_folder}/manipulation_detection.png")
        self.analyze_deception_scores(f"{json_folder}/deception_scores.png")
        
        # 生成统计报告
        self.generate_statistical_report(f"{json_folder}/statistical_report.txt")
        
        print(f"✅ Comprehensive analysis report generated to: {json_folder}")
    
    def generate_statistical_report(self, output_file):
        """生成统计报告"""
        support_changes = self.analyze_support_rate_changes()
        
        with open(output_file, 'w', encoding='utf-8') as f:
            f.write("Big Five Personality Manipulation Experiment Statistical Analysis Report\n")
            f.write("=" * 70 + "\n\n")
            
            # 总体统计
            total_experiments = len(self.results)
            initial_support_rate = np.mean(support_changes['initial_support']) * 100
            final_support_rate = np.mean(support_changes['final_support']) * 100
            support_change = final_support_rate - initial_support_rate
            
            f.write(f"Total experiments: {total_experiments}\n")
            f.write(f"Support rate before manipulation: {initial_support_rate:.1f}%\n")
            f.write(f"Support rate after manipulation: {final_support_rate:.1f}%\n")
            f.write(f"Support rate change: {support_change:+.1f}%\n\n")
            
            # 按人格特征统计
            f.write("Statistics by personality traits:\n")
            f.write("-" * 40 + "\n")
            
            personality_stats = defaultdict(lambda: {'initial': [], 'final': [], 'change': []})
            for i, traits in enumerate(support_changes['personality_traits']):
                for trait, level in traits.items():
                    key = f"{trait}_{level}"
                    personality_stats[key]['initial'].append(support_changes['initial_support'][i])
                    personality_stats[key]['final'].append(support_changes['final_support'][i])
                    personality_stats[key]['change'].append(support_changes['support_rate_change'][i])
            
            for key, stats in personality_stats.items():
                if stats['initial']:
                    avg_initial = np.mean(stats['initial']) * 100
                    avg_final = np.mean(stats['final']) * 100
                    avg_change = avg_final - avg_initial
                    f.write(f"{key}: Before {avg_initial:.1f}% → After {avg_final:.1f}% (Change {avg_change:+.1f}%)\n")
            
            f.write("\nStatistics by manipulation tactics:\n")
            f.write("-" * 40 + "\n")
            
            tactic_stats = defaultdict(lambda: {'initial': [], 'final': [], 'change': []})
            for i, tactic in enumerate(support_changes['tactic_name']):
                tactic_stats[tactic]['initial'].append(support_changes['initial_support'][i])
                tactic_stats[tactic]['final'].append(support_changes['final_support'][i])
                tactic_stats[tactic]['change'].append(support_changes['support_rate_change'][i])
            
            for tactic, stats in tactic_stats.items():
                if stats['initial']:
                    avg_initial = np.mean(stats['initial']) * 100
                    avg_final = np.mean(stats['final']) * 100
                    avg_change = avg_final - avg_initial
                    f.write(f"{tactic}: Before {avg_initial:.1f}% → After {avg_final:.1f}% (Change {avg_change:+.1f}%)\n")
            
            # 操控检测统计
            f.write("\nManipulation detection statistics:\n")
            f.write("-" * 40 + "\n")
            
            detection_stats = {"Detected": 0, "Not Detected": 0}
            for detection in support_changes['manipulation_detection']:
                if "检测到" in detection or "Detected" in detection:
                    detection_stats["Detected"] += 1
                else:
                    detection_stats["Not Detected"] += 1
            
            for status, count in detection_stats.items():
                percentage = (count / total_experiments) * 100
                f.write(f"{status}: {count} experiments ({percentage:.1f}%)\n")
            
            # 欺瞒度分数统计
            f.write("\nDeception score statistics:\n")
            f.write("-" * 40 + "\n")
            
            deception_scores = support_changes['deception_scores']
            avg_deception = np.mean(deception_scores)
            median_deception = np.median(deception_scores)
            min_deception = np.min(deception_scores)
            max_deception = np.max(deception_scores)
            
            f.write(f"Average deception score: {avg_deception:.3f}\n")
            f.write(f"Median deception score: {median_deception:.3f}\n")
            f.write(f"Min deception score: {min_deception:.3f}\n")
            f.write(f"Max deception score: {max_deception:.3f}\n")
            
            # 按策略的欺瞒度统计
            tactic_deception = defaultdict(list)
            for i, tactic in enumerate(support_changes['tactic_name']):
                tactic_deception[tactic].append(support_changes['deception_scores'][i])
            
            f.write("\nAverage deception score by tactic:\n")
            for tactic, scores in tactic_deception.items():
                avg_score = np.mean(scores)
                f.write(f"{tactic}: {avg_score:.3f}\n")

def extract_stance_from_response(response):
    """从响应中提取立场"""
    if not response or response == "No response":
        return "Neutral"
    
    # 首先尝试从【立场】标记中提取
    if "【立场】：" in response:
        stance_text = response.split("【立场】：")[1].split("\n")[0].strip()
        if stance_text in ["Strongly Disagree", "Disagree", "Neutral", "Agree", "Strongly Agree"]:
            return stance_text
    
    # 查找立场关键词
    stance_keywords = {
        "Strongly Disagree": ["Strongly Disagree", "strongly disagree", "完全反对"],
        "Disagree": ["Disagree", "disagree", "一般反对"],
        "Neutral": ["Neutral", "neutral", "中立"],
        "Agree": ["Agree", "agree", "一般支持"],
        "Strongly Agree": ["Strongly Agree", "strongly agree", "完全支持"]
    }
    
    response_lower = response.lower()
    for stance, keywords in stance_keywords.items():
        for keyword in keywords:
            if keyword.lower() in response_lower:
                return stance
    
    return "Neutral"

def main():
    """主函数"""
    import sys
    
    if len(sys.argv) < 2:
        print("Usage: python big5_analysis.py <results_file>")
        print("Example: python big5_analysis.py results/big5_manipulation_experiment_1234567890.json")
        return
    
    results_file = sys.argv[1]
    
    if not os.path.exists(results_file):
        print(f"Error: File {results_file} does not exist")
        return
    
    # 创建分析器
    analyzer = Big5Analysis(results_file)
    
    # 生成综合分析报告
    analyzer.generate_comprehensive_report()

if __name__ == "__main__":
    main()